package com.bins.redis.controller;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.bins.redis.entity.UserEntity;
import com.bins.redis.pubsub.QueueParams;

@RestController
public class RedisController {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private RedisTemplate<String, Serializable> redisTemplate;

	@Autowired
	private QueueParams queueParams;

	@PostMapping("/product/{key}")
	public String product(@PathVariable(name = "key") String key) {
		ListOperations<String, Serializable> redisList = redisTemplate.opsForList();
		long k = Long.parseLong(key);
		queueParams.setSendId(k);
		queueParams.setContent("这是消息内容" + key);
		Long result = redisList.leftPush("queue", JSON.toJSONString(queueParams));
		return String.valueOf(result);
	}

	@PostMapping("/consum/{key}")
	public void consumerMsg(@PathVariable(name = "key") String key) {
		redisTemplate.convertAndSend("andy.channel", "hello world" + key);
	}

	@GetMapping("/get/{key}")
	public String getRedisValue(@PathVariable(name = "key") String key) {
		return stringRedisTemplate.opsForValue().get(key);
	}

	@PostMapping("/set/{key}/{value}")
	public String setRedisValue(@PathVariable(name = "key") String key, @PathVariable(name = "value") String value) {
		stringRedisTemplate.opsForValue().set(key, value);
		return "SUCCESS";
	}

	@GetMapping("/postEntity/{key}")
	public String postEntity(@PathVariable(name = "key") String key) {
		long k = Long.parseLong(key);
		UserEntity user = new UserEntity();
		user.setId(k);
		user.setUserName("Andy" + key);
		user.setNickName("Song" + key);
		redisTemplate.opsForValue().set(String.valueOf(user.getId()), user);
		return "SUCCESS";
	}

	@GetMapping("/getEntity/{key}")
	public Object getEntity(@PathVariable(name = "key") String key) {
		return redisTemplate.opsForValue().get(key);
	}

}
